import { CONFIG } from '@/config/env/dotenv';
import dayjs = require('dayjs');
import { copyFileSync, existsSync, mkdirSync } from 'fs';
import * as fs from 'fs';
import { nanoid } from 'nanoid';
import { extname, join } from 'path';
import { FilePath, Result, UploadFile, UploadStatus } from './upload.interface';

export const ROOT_PATH = process.cwd();

export const isExist = (dirPath = '') => {
  // 判断文件夹是否存在, 不存在创建一个
  if (!existsSync(dirPath)) {
    mkdirSync(dirPath, {
      recursive: true,
    });
  }
};

// 复制文件
export function copyFile(from = '', toFolder = '', toItem = '') {
  isExist(toFolder);
  copyFileSync(from, join(toFolder, toItem));
}

/**
 * 获取文件的拓展名
 * @param {*} filename
 * @returns 文件的拓展名
 */
function getExtension(filename = '') {
  // const ext = path.extname(filename || '').split('.');
  return extname(filename);
}

function getFoldarPathForDate() {
  return `${dayjs().format('YYYY')}/${dayjs().format('MM')}/${dayjs().format(
    'DD',
  )}`;
}

function getRandomName() {
  return `${dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS')}-${nanoid()}`;
}

function deleteFile(path: string) {
  try {
    fs.rmSync(path);
  } catch (error) {
    console.error(`上传文件完成后，删除临时文件失败，${error}`);
  }
}

export class DefaultUploadFile extends UploadFile {
  public openRootPath = CONFIG['MY_NEST_APP_UPLOAD_FILE_OPEN_ROOT_PATH'];
  public rootPath = `${ROOT_PATH}${CONFIG['MY_NEST_APP_UPLOAD_FILE_ROOT_PATH']}`;

  public uploadFile(file: Express.Multer.File): FilePath | Promise<FilePath> {
    console.log(file);
    console.log(file.path);
    if (!existsSync(file.path)) {
      throw new Error('上传的文件临时路径找不到文件！');
    }
    const copyDir = getFoldarPathForDate();
    // 获取新文件名
    const fileName = `${getRandomName()}${getExtension(file.path)}`;
    copyFile(file.path, `${this.rootPath}/${copyDir}`, fileName);
    deleteFile(file.path);
    return `${this.openRootPath}/${copyDir}/${fileName}`;
  }

  public deleteFile(filePath: string): Result | Promise<Result> {
    console.log(filePath);
    return {
      code: UploadStatus.SUCCESS,
      message: '',
    };
  }
}
